package com.denghq.projectbuilder.component.basedatacache.builder;

import com.denghq.projectbuilder.component.basedatacache.cache.ICacheDomain;
import com.denghq.projectbuilder.component.msgbus.bus.IMsgProcessor;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 缓存刷新处理类
 */
@Slf4j
@AllArgsConstructor
public class UpdateCacheAction implements IMsgProcessor {

    private ICacheDomain cache;

    private int retryCount;

    private int failRetryMaxSecond;

    private int failRetryMinSecond;

    private ExecutorService executor;

    @Override
    public void execute(String topic, String msg) {

        executor.execute(() -> {
            int i = 0;
            Random r = new Random();
            while (i <= retryCount) {
                try {
                    //随机睡一会，避免大量请求同时发出,出现请求热点
                    TimeUnit.MILLISECONDS.sleep(r.nextInt(200));
                    int count = cache.update(msg);
                    cache.setLoadSuccess(true);
                    log.info("接收到MQ消息【{}】变更,重新获取基础数据缓存-【{} {}】数据,当前缓存（{}）条数据", cache.getTopicName(), cache.getCacheKey(), cache.getCacheName(), count);
                    break;
                } catch (Exception e) {
                    i++;
                    //Random random = new Random();
                    Integer second = r.nextInt(failRetryMaxSecond - failRetryMinSecond) + failRetryMinSecond;
                    log.error("接收到MQ消息【{}】变更,重新获取基础数据缓存-【{} {}】数据发生异常,将在{}s后进行第{4}次重试", cache.getTopicName(), cache.getCacheKey(), cache.getCacheName(), second, i);
                    try {
                        TimeUnit.SECONDS.sleep(second);
                    } catch (InterruptedException el) {
                        log.info("接收到MQ消息【{}】变更,-更新【{} {}】数据休眠被中断,{}", cache.getTopicName(), cache.getCacheKey(), cache.getCacheName(), el.getMessage());
                        break;
                    }
                }
            }
        });
    }
}
